<template>
  <div @mouseleave="leave()" @mousemove="mousemove()" data-app="true">
    <div id="video" ref="videowindow">
      <div v-if="ifpoptext" id="poptextdiv" ref="poptextdiv"></div>
      <video
        :src="this.initVideo.url"
        preload="auto"
        ref="video"
        id="player"
        :style="playerHeight"
        webkit-playsinline
        @click="playOrPause"
        @canplay="videoCanPlay()"
        @timeupdate="videoTimeUpdate()"
        @ended="videoEnd()">  
      </video>
      <transition>
        <div id="control" v-if="showControl" ref="control">
          <el-slider class="timeline" v-model="initVideo.currentTime" :max="initVideo.videoLength" :show-tooltip="false" @change="changeVideoTime"></el-slider>
          <el-row>
            <el-col :span="2">
              <el-button type="text" @click="playOrPause" id="play-btn">
                <i v-if="playState === 'play'" style="font-size: 20px" class="iconfont icon-icon_play p-icon" />
                <i v-if="playState === 'pause'" style="font-size: 20px" class="iconfont icon-zanting" />
                <i v-if="playState === 'replay'" style="font-size: 20px" class="iconfont icon-shuaxin" />
              </el-button>
            </el-col>
            <div class="time-text"> {{ initVideo.currentTime | videoTime }} /{{ initVideo.videoLength | videoTime }}</div>
            <!--倍速-->
            <el-button type="text" @click="(showSpeedMenu = !showSpeedMenu),(showvolume = false),(showSetting = false)" class="speed-btn">
              <span class="el-dropdown-link" style="color: #fff">{{ initVideo.speedText}}</span>
            </el-button>
            <transition>
              <el-card v-if="showSpeedMenu" id="speed">
                <el-row>
                  <el-button type="text" style="color: #fff" @click="handleCommand(0.5)">0.5x</el-button>
                  <el-button type="text" style="color: #fff" @click="handleCommand(0.75)">0.75x</el-button>
                  <el-button type="text" style="color: #fff" @click="handleCommand(1)">1.0x</el-button>
                  <el-button type="text" style="color: #fff" @click="handleCommand(1.25)">1.25x</el-button>
                  <el-button type="text" style="color: #fff" @click="handleCommand(1.5)">1.5x</el-button>
                  <el-button type="text" style="color: #fff" @click="handleCommand(2)">2.0x</el-button>
                </el-row>
              </el-card>
            </transition>
            <!--音量-->
            <el-button type="text" @click="(showvolume = !showvolume),(showSpeedMenu = false),(showSetting = false)" class="volume-btn">
              <i style="color: #fff;font-size:20px" class="iconfont icon-yinliang1" />
            </el-button>
            <transition>
              <el-card v-if="showvolume" id="volume">
                    <el-slider style="margin-left:-18px" height="120px" v-model="volume" @change="changevolume" vertical :max="100" :min="0"></el-slider>
              </el-card>
            </transition>
            <!--全屏-->
            <el-button type="text" @click="fullScreen" class="full-screen">
              <i style="color: #fff;font-size:20px" class="el-icon-full-screen" />
            </el-button>
          </el-row>
        </div>
      </transition>
    </div>
    <!--弹幕发送区-->
    <el-row class="danmu">
      <el-card v-if="showSetting" class="danmu-set">
        <el-row><p class="setting-text">弹幕颜色</p></el-row>
        <el-row>
          <div class="color-btn btn-white" @click="setColor('#808080')"></div>
          <div class="color-btn btn-red" @click="setColor('#e54256')"></div>
          <div class="color-btn btn-yellow" @click="setColor('#ffe133')"></div>
          <div class="color-btn btn-green" @click="setColor('#64DD17')"></div>
          <div class="color-btn btn-blue" @click="setColor('#39ccff')"></div>
          <div class="color-btn btn-purple" @click="setColor('#D500F9')"></div>
        </el-row>
        <el-row><p class="setting-text">弹幕类型</p></el-row>
        <el-row>
          <el-switch v-model="type" active-value="row" active-text="滚动" inactive-value="fixed" inactive-text="固定"></el-switch>
        </el-row>
        <el-row><p class="setting-text">弹幕透明度</p></el-row>
        <el-row>
          <el-slider v-model="poptextop" :max="100" :min="0" :show-tooltip="false"></el-slider>
        </el-row>
      </el-card>
      <el-col :span="3" :offset="1">
        <div class="danmu-switch">
          <p>弹幕</p>
          <el-switch v-model="ifpoptext"></el-switch>
        </div>
      </el-col>
      <el-col :span="1">
        <el-button type="text" @click="(showvolume = false),(showSpeedMenu = false),(showSetting = !showSetting)">
          <i :style="settingColor" class="el-icon-s-tools danmu-setting" />
        </el-button>
      </el-col>
      <el-col :span="19">
        <div style="float:right;margin-top:2px">
        <el-input v-model="sendertext" placeholder="发送弹幕" class="danmu-input"></el-input>
        <el-button type="primary" icon="iconfont icon-send" @click="sendDanmu">发送</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { sendDanmu, getDanmu } from "@/api/danmu";
export default {
  name: "wPlayer",
  props: {
    url: {
      type: String,
      default: null,
    },
    videoId: {
      type: Number,
      default: null,
    },
  },
  data() {
    return {
      danmuList: [], //弹幕
      colorpicker: "#fff", //默认弹幕颜色
      isrow: true, //默认发送滚动弹幕
      isFull: false, // 是否全屏
      playerHeight:"max-height:600px",//非全屏下的高度限制
      type: "row", //弹幕类型
      sendertext: "", //默认弹幕文字
      poptextop: 0, //弹幕透明度
      showsendersetting: false, //默认是否打开发送设置
      showSetting: false, //默认是否打开弹幕设置
      settingColor: {
        color: "#808080",
      },
      nowTime: "00:00", //当前时间
      allowoverwrite: true, //允许弹幕溢出覆盖
      channelmax: 23, //默认最大弹道数
      channelrow: 23, //目前滚动弹道数
      channeltop: 23, //目前竖直固定弹道数
      ifpoptext: true, //默认是否显示弹幕
      ifpause: false,
      playState: "play", //播放状态
      showControl: true, //显示控制栏
      volume: 100, //音量
      showvolume: false, //显示音量调节
      showSpeedMenu: false, //显示倍速菜单
      initVideo: {
        currentTime: 0, //当前播放时间
        videoLength: 0, //时长
        speedText: "倍速",
        play: false, //播放还是暂停 true播放中
        url: this.url, //视频Url
        lastTime: null, //标记时间戳
      },
      danmuForm: {
        vid: Number,
        text: "",
        time: "",
        color: "",
        type: "",
      },
    };
  },
  methods: {
    playOrPause() {
      if (this.initVideo.play) {
        //暂停
        this.$refs.video.pause();
        this.playState = "play";
        this.ifpause = false;
      } else if (this.playState == "replay") {
        this.$refs.video.currentTime = 0;
        this.$refs.video.play();
        this.playState = "pause";
        this.ifpause = true;
      } else {
        this.$refs.video.play();
        this.playState = "pause";
        this.ifpause = true;
      }
      this.initVideo.play = !this.initVideo.play;
    },
    //播放完成
    videoEnd() {
      this.playState = "replay";
      this.initVideo.play = false;
      this.ifpause = false;
    },
    //获取视频时长
    videoCanPlay() {
      var duration = this.$refs.video.duration;
      //取整 保证进度条能够走完
      this.initVideo.videoLength = parseInt(duration);
    },
    //更新进度时间
    videoTimeUpdate() {
      var currTime = this.$refs.video.currentTime;
      this.initVideo.currentTime = currTime;
      var m = parseInt((currTime % 3600) / 60);
      var s = parseInt(currTime % 60);
      m = m < 10 ? "0" + m : m;
      s = s < 10 ? "0" + s : s;
      this.nowTime = m + ":" + s;
    },
    //改变视频时间
    changeVideoTime(val) {
      if (this.$refs.video) {
        this.$refs.video.currentTime = val;
      }
    },
    //改变音量
    changevolume() {
      this.$refs.video.volume = this.volume / 100;
    },
    //倍速
    handleCommand(command) {
      this.$refs.video.playbackRate = command;
      if (command != 1) {
        this.initVideo.speedText = command + "x";
      } else {
        this.initVideo.speedText = "倍速";
      }
      this.showSpeedMenu = false;
    },
    //显示/隐藏控制栏
    leave() {
      if (this.initVideo.play) {
        this.showvolume = false;
        this.showSpeedMenu = false;
        this.showControl = false;
      }
    },
    mousemove() {
      if (!this.showControl) {
        this.showControl = true;
        if (this.initVideo.play) {
          setTimeout(() => {
            this.showvolume = false;
            this.showSpeedMenu = false;
            this.showControl = false;
          }, 3000);
        }
      }
    },
    //全屏
    fullScreen() {
      this.showControl = true;
      this.showvolume = false;
      this.showSpeedMenu = false;
      if (!this.isFull) {
        var doc = document.getElementById("video");
        if (doc.requestFullscreen) {
          doc.requestFullscreen();
        } else if (doc.mozRequestFullScreen) {
          doc.mozRequestFullScreen();
        } else if (doc.webkitRequestFullScreen) {
          doc.webkitRequestFullScreen();
        }
        this.isFull = true;
      } else {
        var exit = document;
        if (exit.exitFullscreen) {
          exit.exitFullscreen();
        } else if (exit.mozCancelFullScreen) {
          exit.mozCancelFullScreen();
        } else if (exit.webkitCancelFullScreen) {
          exit.webkitCancelFullScreen();
        }
        this.isFull = false;
      }
    },
    setColor(color) {
      this.colorpicker = color;
      this.settingColor.color = color;
    },
    //发送弹幕
    sendDanmu() {
      if (this.sendertext.trim() != "") {
        //发送弹幕
        this.danmuForm.text = this.sendertext;
        this.danmuForm.time = this.nowTime;
        this.danmuForm.color = this.colorpicker;
        this.danmuForm.type = this.type;
        sendDanmu(this.danmuForm)
          .then((res) => {
            if (res.data.code === 200) {
              //发送成功
              if (this.danmuForm.type == "row") {
                var channel = this.channelrow;
                var poptextspan1 = document.createElement("span");
                var content = document.createTextNode(this.danmuForm.text);
                poptextspan1.style.border = "2px solid #ff0000";
                poptextspan1.style.fontSize = "20px";
                poptextspan1.style.color = this.colorpicker;
                poptextspan1.style.textAlign = "left";
                poptextspan1.style.position = "absolute";
                poptextspan1.style.top =
                  String((this.channelmax - channel) * 22) + "px";
                poptextspan1.style.textShadow = "-2px 2px #000";
                poptextspan1.style.whiteSpace = "nowrap";
                poptextspan1.classList.add("start");
                poptextspan1.style.animation =
                  "mov " + String(40 - this.danmuForm.text.length * 0.2) + "s";
                poptextspan1.style.animationPlayState = "paused";
                poptextspan1.appendChild(content);
                document.getElementById("poptextdiv").appendChild(poptextspan1);
                this.channelrow--;
                var t1 = setInterval(() => {
                  if (this.ifpause) {
                    if (poptextspan1.style.animationPlayState == "paused") {
                      poptextspan1.style.animationPlayState = "running";
                    }
                  } else {
                    if (poptextspan1.style.animationPlayState == "running") {
                      poptextspan1.style.animationPlayState = "paused";
                    }
                  }
                }, 100);
                poptextspan1.addEventListener("animationend", () => {
                  clearInterval(t1);
                  document
                    .getElementById("poptextdiv")
                    .removeChild(poptextspan1);
                });
              } else {
                if (this.danmuForm.type == "fixed") {
                  var channel2 = this.channeltop;
                  var poptextspan2 = document.createElement("span");
                  var content2 = document.createTextNode(this.danmuForm.text);
                  poptextspan2.style.color = this.danmuForm.color;
                  poptextspan2.style.position = "absolute";
                  poptextspan2.style.fontSize = "20px";
                  poptextspan2.style.textAlign = "center";
                  poptextspan2.style.width = "100%";
                  poptextspan2.style.textShadow = "-2px 2px #000";
                  poptextspan2.style.top =
                    String((this.channelmax - channel2) * 22) + "px";
                  poptextspan2.appendChild(content2);
                  document
                    .getElementById("poptextdiv")
                    .appendChild(poptextspan2);
                  this.channeltop--;
                  var nowtime = this.$refs.video.currentTime + 5;
                  var t2 = window.setInterval(() => {
                    if (this.$refs.video.currentTime > nowtime) {
                      document
                        .getElementById("poptextdiv")
                        .removeChild(poptextspan2);
                      clearInterval(t2);
                    }
                  }, 100);
                }
              }
            } else {
              this.$message.error("发送失败");
            }
          })
          .catch((err) => {
            this.$message.error(err.response.data.msg);
          });
        this.sendertext = "";
      } else {
        this.$message.error("请输入弹幕");
      }
    },
    //弹幕开关
    danmuSwitch() {
      this.ifpoptext = !this.ifpoptext;
      if (this.ifpoptext) {
        this.$message("弹幕已开启");
      } else {
        this.$message("弹幕已关闭");
      }
    },
    _gatDanmu() {
      if (this.ifpoptext) {
        getDanmu(this.videoId).then((res) => {
          if (res.data.code === 200) {
            this.danmuList = res.data.data;
          }
        });
      }
    },
    //生成弹幕
    poptextCreater(type, channel, color, text) {
      if (type == "row") {
        var poptextspan = document.createElement("span");
        var content = document.createTextNode(text);
        poptextspan.style.fontSize = "20px";
        poptextspan.style.color = color;
        poptextspan.style.textAlign = "left";
        poptextspan.style.position = "absolute";
        poptextspan.style.top = String((this.channelmax - channel) * 22) + "px";
        poptextspan.style.textShadow = "-2px 2px #000";
        poptextspan.style.whiteSpace = "nowrap";
        poptextspan.classList.add("start");
        poptextspan.style.animation =
          "mov " + String(40 - text.length * 0.2) + "s";
        poptextspan.style.animationPlayState = "paused";
        poptextspan.appendChild(content);
        document.getElementById("poptextdiv").appendChild(poptextspan);
        this.channelrow--;
        var t1 = setInterval(() => {
          if (this.ifpause) {
            if (poptextspan.style.animationPlayState == "paused") {
              poptextspan.style.animationPlayState = "running";
            }
          } else {
            if (poptextspan.style.animationPlayState == "running") {
              poptextspan.style.animationPlayState = "paused";
            }
          }
        }, 100);
        poptextspan.addEventListener("animationend", () => {
          clearInterval(t1);
          document.getElementById("poptextdiv").removeChild(poptextspan);
        });
      } else {
        var poptextspan2 = document.createElement("span");
        var content2 = document.createTextNode(text);
        poptextspan2.style.color = color;
        poptextspan2.style.position = "absolute";
        poptextspan2.style.fontSize = "20px";
        poptextspan2.style.textAlign = "center";
        poptextspan2.style.width = "100%";
        poptextspan2.style.textShadow = "-2px 2px #000";
        poptextspan2.style.top =
          String((this.channelmax - channel) * 22) + "px";
        poptextspan2.appendChild(content2);
        document.getElementById("poptextdiv").appendChild(poptextspan2);
        this.channeltop--;
        var nowtime = this.$refs.video.currentTime + 5;
        var t2 = window.setInterval(() => {
          if (this.$refs.video.currentTime > nowtime) {
            document.getElementById("poptextdiv").removeChild(poptextspan2);
            clearInterval(t2);
          }
        }, 100);
        //计时器，设定5s后删除此时间点的弹幕
      }
    },
  },
  watch: {
    nowTime(time) {
      //弹幕池刷新
      this.channelrow = this.channelmax;
      this.channeltop = this.channelmax;
      for (var i = 0, l = this.danmuList.length; i < l; i++) {
        if (this.danmuList[i].time == time) {
          if (this.danmuList[i].type == "fixed") {
            this.poptextCreater(
              "fixed",
              this.channeltop,
              this.danmuList[i].color,
              this.danmuList[i].text
            );
          } else {
            this.poptextCreater(
              "row",
              this.channelrow,
              this.danmuList[i].color,
              this.danmuList[i].text
            );
          }
        }
      }
    },
    isFull(){
      if(this.isFull){
        this.playerHeight=""
      }else{
        this.playerHeight="max-height:600px"
      }
    },
    //设置弹幕透明度
    poptextop() {
      document.getElementById("poptextdiv").style.opacity =
        parseFloat(100 - this.poptextop) * 0.01;
    },
  },
  created() {
    this.danmuForm.vid = this.videoId;
    this._gatDanmu();
  },
  filters: {
    videoTime(time) {
      var m = parseInt((time % 3600) / 60);
      var s = parseInt(time % 60);
      m = m < 10 ? "0" + m : m;
      s = s < 10 ? "0" + s : s;
      return m + ":" + s;
    },
  },
};
</script>

<style>
#video {
  position: relative;
}

#poptextdiv {
  position: absolute;
  overflow: hidden;
  width: 100%;
  height: 100%;
}

#player{
  width: 100%;
  height: 100%;
  background-color: black;
}

#control {
  /*opacity: 0;*/
  position: absolute;
  z-index: 6;
  width: 100%;
  height: 50px;
  background: linear-gradient(rgba(0, 0, 0, 0), #000);
  bottom: 0;
  transition: opacity 1s;
  -moz-transition: opacity 1s; /* Firefox 4 */
  -webkit-transition: opacity 1s; /* Safari 和 Chrome */
  -o-transition: opacity 1s; /* Opera */
}

.timeline {
  position: absolute;
  width: 100%;
  top: -20px;
}

#play-btn {
  color: #fff;
  margin-left: 20px;
  margin-top: 5px;
}

.time-text {
  color: #fff;
  padding-top: 16px;
}

#poptextsetting {
  z-index: 6;
  position: absolute;
  right: 70px;
  width: 190px;
  bottom: 60px;
  background: rgba(0, 0, 0, 0.5);
}

.setting-text{
  color: #fff;
}

.color-btn{
  float: left;
  width: 26px;
  height: 26px;
  border-radius: 50%;
  margin: 0 0 5px 5px;
}

.btn-white {
  background-color: white;
}

.btn-red {
  background-color: #e54256;
}

.btn-yellow {
  background-color: #ffe133;
}

.btn-green {
  background-color: #64dd17;
}

.btn-blue {
  background-color: #39ccff;
}

.btn-purple {
  background-color: #d500f9;
}

.speed-btn {
  position: absolute;
  right: 110px;
  font-size: 16px;
  top: 8px;
}

#speed {
  position: absolute;
  bottom: 60px;
  right: 30px;
  border-color: transparent;
  background: rgba(0, 0, 0, 0.5);
}

.volume-btn {
  position: absolute;
  right: 60px;
  top: 5px;
}

#volume {
  z-index: 6;
  position: absolute;
  width: 40px;
  right: 50px;
  bottom: 60px;
  background: rgba(0, 0, 0, 0.7);
}
.full-screen {
  position: absolute;
  right: 12px;
  top: 5px;
}

.danmu{
  background-color: #fff;
  height: 50px;
  position: relative;
}

.danmu-switch{
  white-space: nowrap;
  width: 200px;
}

.danmu-switch>p{
  margin-top: 14px;
  width: 40px;
  float: left;
}

.danmu-switch>div{
  margin: 14px 0 0 5px;
}

.danmu-setting{
  font-size: 24px;
}

.danmu-input{
  width: 540px
}

.danmu-set{
  z-index: 8;
  bottom: 50px;
  left: 40px;
  position: absolute;
  background: rgba(0, 0, 0, 0.8);
  width: 230px;
  height: 280px;
}

@keyframes mov {
  from {
    right: -200px;
  }
  to {
    right: 3000px;
  }
}

@-moz-keyframes mov /* Firefox */ {
  from {
    right: -200px;
  }
  to {
    right: 3000px;
  }
}

@-webkit-keyframes mov /* Safari 和 Chrome */ {
  from {
    right: -200px;
  }
  to {
    right: 3000px;
  }
}
@-o-keyframes mov /* Opera */ {
  from {
    right: -200px;
  }
  to {
    right: 3000px;
  }
}
</style>